package controller.pages;

import base.R;
import lombok.SneakyThrows;
import utils.ExceptionUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/page/*")
public class UnifiedPageController extends HttpServlet {

    private String extractAction(String uri) {
        String[] parts = uri.split("/");
        return parts[parts.length - 1];
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            String page = extractAction(req.getRequestURI());
            String pagePath = "/pages/" + page + ".jsp";

            // 检查页面是否存在
            if (!pageExists(pagePath)) {
                resp.sendRedirect("/404");
                return;
            }

            req.getRequestDispatcher(pagePath).forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            R.error().setMsg("请求时出现异常: " + ExceptionUtil.getExceptionMessage(e)).push(resp);
        }
    }

    /**
     * 检查页面是否存在
     */
    @SneakyThrows
    private boolean pageExists(String pagePath) {
        return getServletContext().getResource(pagePath) != null;
    }
}
